package com.aboverock.core.orm.mybatisplus;

import com.aboverock.autoconfigure.util.JwtUtil;
import com.aboverock.common.enums.DomainDeletedEnum;
import com.aboverock.core.spring.SpringWebHolder;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * The Class BaseMetaObjectHandler.
 *
 * @author Rock Wang
 */
@Component
public class BaseMetaObjectHandler implements MetaObjectHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();

        // 设置创建时间
        setFieldValByName("createTime", date, metaObject);
        // 设置创建用户
        HttpServletRequest request = null;
        try {
            request = SpringWebHolder.getRequest();
        } catch (Exception e) {
            logger.warn("Data-Smart：{}", e.getMessage());
        }

        if (request != null) {
            String loginName = JwtUtil.getLoginName();
            if (loginName != null) {
                setFieldValByName("createUser", loginName, metaObject);
            }
        }
        // 设置更新时间
        setFieldValByName("updateTime", date, metaObject);

        // 设置删除状态
        Object deleted = getFieldValByName("deleted", metaObject);
        if (null == deleted) {
            setFieldValByName("deleted", DomainDeletedEnum.NORMAL.getStatus(), metaObject);
        }
        // 设置初始版本
        Object version = getFieldValByName("version", metaObject);
        if (null == version) {
            setFieldValByName("version", 0, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 设置更新时间
        setFieldValByName("updateTime", new Date(), metaObject);
        // 设置更新用户
        HttpServletRequest request = null;
        try {
            request = SpringWebHolder.getRequest();
        } catch (Exception e) {
            logger.warn("Data-Smart：{}", e.getMessage());
        }

        if (request != null) {
            String loginName = JwtUtil.getLoginName();
            if (loginName != null) {
                setFieldValByName("updateUser", loginName, metaObject);
            }
        }
    }

}
